package dyyx.util;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

public abstract class ConfigUtil {

	// private static final String CONFIG = "config.properties";
	
	
    private static volatile Properties config = null;
    
    static{
    	Properties prop = readProperties();   
    	config = prop;
    }
    
    
    private static Properties readProperties(){
    	String file = WebUtil.getWebRootDir()+"/WEB-INF/config.properties";
    	Properties prop = CommUtil.readPropertiesByPath(file);
    	return prop;
    }
    
    
    public static String get(String key){
    	if(CommUtil.isBlank(key)){
    		return null;
    	}
    	String value = config.getProperty(key);
    	if(value!=null){
    		value = value.trim();
    	}
    	return value;
    }
    
    public static String get(String prefix,String key){
    	if(CommUtil.isBlank(prefix) || CommUtil.isBlank(key)){
    		return null;
    	}
    	String value = config.getProperty(prefix + "."+key);
    	if(value!=null){
    		value = value.trim();
    	}
    	return value;
    }
    
    public static int getInt(String key){
    	if(CommUtil.isBlank(key)){
    		return 0;
    	}
    	
    	return CommUtil.getInt(get(key));
    }
    
    public static long getLong(String key){
    	if(CommUtil.isBlank(key)){
    		return 0;
    	}
    	
    	return CommUtil.getLong(get(key));
    }
    
   
    public static Map<String,String> getAllConfig(){
    	Map<String,String> map = new HashMap(config);
    	return map;
    }
    
    public static Set<String> getValueAsSet(String name){
    	if(CommUtil.isBlank(name)){
    		return null;
    	}
    	String str = get(name);
    	if(CommUtil.isBlank(str)){
    		return null;
    	}
    	String[]arr = StringUtils.split(str, ",");
    	if(arr==null || arr.length<=0){
    		return null;
    	}
    	Set<String> values = new LinkedHashSet<String>();
    	for(String item:arr){
    		if(StringUtils.isBlank(item)){
    			continue;
    		}
    		item = item.trim();
    		values.add(item);
    	}
    	
    	return values; 	
    }
    
    
    public static synchronized void reload(){
    	Properties prop = readProperties();   
    	config = prop;
    	RunStatusUtil.updateCount("configReloadCount");
    	RunStatusUtil.logInfo("configReloadInfo", LocalDateTime.now().toString());
    }
    
    
    

}